﻿using System;
using System.ComponentModel;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SLConnectedWebPart.SLConProviderPart
{
    [ToolboxItemAttribute(false)]
    public class SLConProviderPart : WebPart, ISPListItem, IPostBackEventHandler 
    {
        int _ID;
        string _name;
        ClientScriptManager cs;
        HiddenField sourceID;
        HiddenField sourceName;
        
        public void RaisePostBackEvent(string eventArgument)
        {

            if (eventArgument == "@@connect")
            {
                itemSelected();
            }
        }

        private void itemSelected()
        {
            //get hidden fields and set the provider interface values during a postback   
            _ID = int.Parse(sourceID.Value);
            _name = sourceName.Value;
        }
        
        protected override void CreateChildControls()
        {
            //add hidden fields
            sourceID = new HiddenField();
            sourceName = new HiddenField();

            this.Controls.Add(sourceID);
            this.Controls.Add(sourceName);

            cs = Page.ClientScript;
            //cs.RegisterHiddenField(ClientID + "sourceID", "");
            //cs.RegisterHiddenField(ClientID + "sourceName", "");
            //cs.RegisterStartupScript(this.GetType(), "SLPart", emitScript(), true);

            System.Web.UI.HtmlControls.HtmlGenericControl si = new System.Web.UI.HtmlControls.HtmlGenericControl();
            si.TagName = "script";
            si.Attributes.Add("type", @"text/javascript");
            si.InnerHtml = emitScript();
            this.Page.Header.Controls.Add(si);

            

            //load the SL XAP file
            //first build object markup
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<div id='silverlightControlHost'>");
            sb.AppendLine("<object data=\"data:application/x-silverlight-2,\" type=\"application/x-silverlight-2\" width=\"100%\" height=\"100%\">");
            sb.AppendLine("<param name=\"source\" value=\"/_app_bin/SLPartApp.xap\"/>");
            sb.AppendLine("<param name=\"onError\" value=\"onSilverlightError\" />");
            sb.AppendLine("<param name=\"background\" value=\"white\" />");
            sb.AppendLine("<param name=\"minRuntimeVersion\" value=\"3.0.40818.0\" />");
            sb.AppendLine("<param name=\"autoUpgrade\" value=\"true\" />");
            //sb.AppendFormat("<param name=\"selectedItem\" value\"{0}\" />\r\n",_ID);//this param tells the silverlight what the current item is after postback
            sb.AppendLine("<a href=\"http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40818.0\" style=\"text-decoration:none\">");
            sb.AppendLine("  <img src=\"http://go.microsoft.com/fwlink/?LinkId=161376\" alt=\"Get Microsoft Silverlight\" style=\"border-style:none\"/>");
            sb.AppendLine("</a></object></div>");
            
            //create tag with literal control
            Literal SL = new Literal();
            SL.Text = sb.ToString();
            this.Controls.Add(SL);


        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

        }

        //create the script that will set the hidden fields and postback
        private string emitScript()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine();
            sb.AppendLine("// <![CDATA[ ");
            sb.AppendLine("function passBack(myID, myName){");
            sb.AppendLine(String.Format("var sourceId = document.getElementById('{0}');",sourceID.ClientID)); 
            sb.AppendLine(String.Format("var sourceName = document.getElementById('{0}');",sourceName.ClientID));
            sb.AppendLine("sourceId.value = myID;");
            sb.AppendLine("sourceName.value = myName;");
            sb.AppendFormat("{0};\r\n", cs.GetPostBackEventReference(this, "@@connect")); 
            sb.AppendLine("}");
            sb.AppendLine("function getValue(){");
            sb.AppendLine(String.Format("return document.getElementById('{0}').value;", sourceID.ClientID));
            sb.AppendLine("}");
            sb.AppendLine("// ]]>");

            return sb.ToString();

        }

        //Provider web part interface
        [ConnectionProvider("ListItem Name and ID")]
        public ISPListItem GetConnectionInterface()
        {
            return this;
        }

        int ISPListItem.ID
        {
            get { return _ID; }
        }

        string ISPListItem.Name
        {
            get { return _name; }
        }



    }
}
